﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Portal.HtmlTool;
using NetDon.Utilities.ExcelExport;
using NetDon.eBoss.Data.CollectionClasses;
using NetDon.eBoss.Data.EntityClasses;
using NetDon.eBoss.Data.HelperClasses;
using NetDon.eBoss.Portal.Common;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.eBoss.Portal.HtmlTool
{

    public partial class TemplatenList : NetDonPage
    {
        HtmlToolService _htmlToolService = new HtmlToolService();
        HtmlToolAccountService _htmlToolAccountService = new HtmlToolAccountService();
        protected void Page_Load(object sender, EventArgs e)
        {
            btnBatchModifyDesc.Attributes.Add("onclick", "batchModifyOrder('{0}');return false;".Formato(this.gridCustomerInfoList.ClientID));
            btnBatchModifyTag.Attributes.Add("onclick", "batchModifyTag('{0}');return false;".Formato(this.gridCustomerInfoList.ClientID));
            PageQueryAdapter1.PageSize = 100;
            if (!IsPostBack)
            {
                ddlHtmlToolCategory.InsertEmptyItem(ListEmptyType.Select);
                PageQueryAdapter1.PerformQuery();

            }
        }
        private static readonly string[] AvialableFileExtensions = new[]
                                                              {
                                                                  // Office Open XML
                                                                  ".XLSX", ".XLSM",
                                                                  // Excel Binary
                                                                  ".XLSB",
                                                                  // Excel 97-2003
                                                                  ".XLS"
                                                              };
        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new HtmlToolCriteria
            {

                Tag = ddlRouteTypeId.SelectedValue.ToInt32(),
                Color = txtColor.Text.Trim(),
                ItemNo = txtItemNo.Text.Trim(),
                ProductName = txtProductName.Text.Trim(),
                Trademark = txtTrademark.Text.Trim(),
                Style = txtStyle.Text.Trim(),
                CategoryRuleId = ddlHtmlToolCategory.SelectedValue.ToInt32()


            };

            e.Condition = criteria;
        }

        public void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();



        }
        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            e.RecordCount = new HtmlToolService().GetCustomerInfoCount((HtmlToolCriteria)e.Condition);
        }

        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            e.DataSource = new HtmlToolService().SearchCustomerInfoDatasByCondition((HtmlToolCriteria)e.Condition, gridCustomerInfoList.SortExpression,
                                                      gridCustomerInfoList.SortDirection, e.PageSize, e.PageIndex);
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var id = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));

                var accountId = e.Row.Attributes["Accountid"] = Convert.ToString(DataBinder.Eval(entity, "Accountid"));

                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = string.Format("modifyCustomer('{0}','{1}');return false;", id, accountId);
                }

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteDemand('{0}');return false;", id);
                }
            }
        }
        protected void btnDeleteDemand_Click(object sender, EventArgs e)
        {

            var customerId = fieldCustomerId.Value.ToInt32();

            bool result = new HtmlToolService().RemoveProductGroups(customerId.Value);

            if (result)
            {
                PageQueryAdapter1.PerformQuery();
                Alert("删除成功!");
            }
            else
            {
                Alert("删除失败！");
            }
        }
        protected void btnBatchDelete_Click(object sender, EventArgs e)
        {

            IList<int> ids = new List<int>();
            if (GetSelectedIdLists(out ids))
            {
                bool result = new HtmlToolService().RemoveTemplates(ids);
                if (result)
                {
                    PageQueryAdapter1.PerformQuery();
                    Alert("删除成功!");
                }
                else
                {
                    Alert("删除失败！");
                }

            }

        }
        private bool GetSelectedIdLists(out IList<int> ids)
        {
            ids = new List<int>();
            foreach (GridViewRow row in this.gridCustomerInfoList.Rows)
            {
                var chkSelected = (CheckBox)row.FindControl("chkSelect");
                if (chkSelected != null)
                {
                    if (chkSelected.Checked)
                    {
                        int id = Convert.ToInt32(row.Attributes["Id"]);

                        ids.Add(id);
                    }
                }
            }
            if (ids.Count <= 0)
            {
                Alert("请至少选择一笔记录。");
                return false;
            }

            return true;
        }


        protected void btnImportTemplate_Click(object sender, EventArgs e)
        {
            if (!FileUpload1.HasFile)
            {
                Alert("请选择要导入的出单信息文件.");
                return;
            }
            string extension = Path.GetExtension(FileUpload1.FileName);
            if (AvialableFileExtensions.FirstOrDefault(i => string.Compare(i, extension, true) == 0) == null)
            {
                Alert("请选择正确的Excel文件.");
                return;
            }

            string filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(FileUpload1.FileName));
            FileUpload1.SaveAs(filePath);
            var data = DataImportService.ReadExcelData(filePath);
            // 1st step: check whether the uploaded excel file has data.
            if (!HasData(data))
            {
                Alert("你导入的Excel文件没有数据.");
                return;
            }
            try
            {
                //2st insert data
                ImportData(data);
                Alert("导入成功");
                PageQueryAdapter1.PerformQuery();
            }
            catch (ApplicationException ex)
            {

                Alert("导入的数据有问题，请核实." + ex.Message);
            }
            catch (Exception ex)
            {

                Alert("导入失败." + ex.Message);
            }
        }

        private void ImportData(IList<ProductgroupEntity> data)
        {
            var service = new HtmlToolService();
            foreach (var productgroupEntity in data)
            {
                var existingProductGroupEntity = Extract(productgroupEntity);
                if (existingProductGroupEntity == null)
                {
                    //update sourceId as Id for default account
                    productgroupEntity.Accountid = new HtmlToolAccountService().GetHtmlToolDefaultAccount().Id;

                    //auto guess PicUrl
                    AutoDetectPicUrl(productgroupEntity);
                    AutoDetectHtmlToolCategory(productgroupEntity);
                    productgroupEntity.Save();
                    productgroupEntity.Sourceid = productgroupEntity.Id;
                    productgroupEntity.Save();
                    existingProductGroupEntity = productgroupEntity;
                }
                //clone all other accounts
                service.CloneAllOtherAccounts(existingProductGroupEntity);
                //color setting
                service.InsertTitleColorSetting(productgroupEntity.Color);
                //size setting
                service.InsertSizeSetting(productgroupEntity.Size);
            }
        }
        private void AutoDetectHtmlToolCategory(ProductgroupEntity productgroupEntity)
        {
            var entity = new HtmlToolService().GetHtmltoolCategoryBySize(productgroupEntity.Size);
            if (entity != null)
            {
                productgroupEntity.Categoryruleid = entity.Id;
            }
        }

        private void AutoDetectPicUrl(ProductgroupEntity productgroupEntity)
        {

            Regex re = new Regex(@".+-[1-9]+$");
            if (re.IsMatch(productgroupEntity.Itemno))
            {
                productgroupEntity.Picurl1 = productgroupEntity.Itemno + "_1.jpg";
                productgroupEntity.Picurl2 = productgroupEntity.Itemno + "_2.jpg";
                productgroupEntity.Picurl3 = productgroupEntity.Itemno + "_3.jpg";
                productgroupEntity.Picurl4 = productgroupEntity.Itemno + "_4.jpg";
                productgroupEntity.Picurl5 = productgroupEntity.Itemno + "_5.jpg";
                productgroupEntity.Picurl6 = productgroupEntity.Itemno + "_6.jpg";
                productgroupEntity.Picurl7 = productgroupEntity.Itemno + "_7.jpg";
            }

        }
        private ProductgroupEntity Extract(ProductgroupEntity productgroupEntity)
        {
            return Extract(productgroupEntity, _htmlToolAccountService.GetHtmlToolDefaultAccount());
        }

        private ProductgroupEntity Extract(ProductgroupEntity productgroupEntity, HtmltoolaccountEntity htmltoolaccount)
        {
            if (!string.IsNullOrWhiteSpace(productgroupEntity.Productname))
            {
                var array = productgroupEntity.Productname.Split(new char[] { ' ' });
                productgroupEntity.Color = array[1].Trim();
                productgroupEntity.Itemno = array[0].Trim();
                productgroupEntity.Productname =
                productgroupEntity.Productname.Replace(array[0], "").Replace(array[1], "").Replace(array[2], "").Replace(array[3], "").Trim();
                return _htmlToolService.GetProductGroupByItemNoAndColor(productgroupEntity.Itemno, productgroupEntity.Color, htmltoolaccount.Id);

            }
            return null;
        }


        private static bool HasData(IList<ProductgroupEntity> ds)
        {
            if (ds == null)
            {
                return false;
            }
            if (ds.Count == 0)
            {
                return false;
            }
            return true;
        }


        protected void btnImportProduct_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ddlAcount.SelectedValue))
            {
                Alert("请选择账号.");
                return;
            }
            if (!FileUpload2.HasFile)
            {
                Alert("请选择要导入的出单信息文件.");
                return;
            }
            string extension = Path.GetExtension(FileUpload2.FileName);
            if (AvialableFileExtensions.FirstOrDefault(i => string.Compare(i, extension, true) == 0) == null)
            {
                Alert("请选择正确的Excel文件.");
                return;
            }

            string filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(FileUpload1.FileName));
            FileUpload2.SaveAs(filePath);
            var data = DataImportService.ReadExcelData(filePath);
            // 1st step: check whether the uploaded excel file has data.
            if (!HasData(data))
            {
                Alert("你导入的Excel文件没有数据.");
                return;
            }

            try
            {
                //2st insert data
                Export(data);
            }
            catch (ApplicationException ex)
            {

                Alert("导入的数据有问题，请核实." + ex.Message);
            }
            catch (Exception ex)
            {

                Alert("导入失败." + ex.Message);
            }

        }
        void Export(IList<ProductgroupEntity> data)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Custom Label");
            dt.Columns.Add("Description");
            dt.Columns.Add("PicURL");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("Starting Price");
            dt.Columns.Add("Size");
            //new
            dt.Columns.Add("Category");
            dt.Columns.Add("Color");
            dt.Columns.Add("Style");
            dt.Columns.Add("Brand");
            var selectedHtmlAccount = new HtmltoolaccountEntity(ddlAcount.SelectedValue.ToInt32().Value);
            var siteCode = selectedHtmlAccount.Sitecode ?? 0;
            foreach (var productGroup in data)
            {
                var row = dt.NewRow();
                var productGroupFromDB = Extract(productGroup, selectedHtmlAccount);

                row.BeginEdit();
                row["Title"] = GetProductTitle(productGroupFromDB, productGroup, siteCode);
                row["Custom Label"] = productGroup.Productcode;

                row["PicURL"] = productGroupFromDB.Picurl1.GetFullImgUrl();
                row["Quantity"] = productGroup.Quantity;
                row["Starting Price"] = productGroup.Retailprice;
                row["Size"] = productGroup.Size;

                if (!ckbIsForced.Checked)
                {
                    if (!productGroupFromDB.Categoryruleid.HasValue)
                    {
                        throw new ApplicationException(string.Format("设置错误-HtmlTool分类没有选择，商品名称为{0}",
                                                                     productGroup.Productname));
                    }
                    if (!productGroupFromDB.Styleid.HasValue)
                    {
                        throw new ApplicationException(string.Format("设置错误-款式没有选择，商品名称为{0}",
                                                                     productGroup.Productname));
                    }
                    if (!productGroupFromDB.Trademarkid.HasValue)
                    {
                        throw new ApplicationException(string.Format("设置错误-品牌没有选择，商品名称为{0}",
                                                                     productGroup.Productname));
                    }
                }
                row["Category"] = _htmlToolService.GetHtmltoolCategoryById(productGroupFromDB.Categoryruleid);
                row["Color"] = _htmlToolService.GeteBayColorByColor(productGroup.Color, siteCode);
                row["Style"] = _htmlToolService.GeteBayStyleById(productGroupFromDB.Styleid, siteCode);
                row["Brand"] = _htmlToolService.GetTradeMarkById(productGroupFromDB.Trademarkid);
                row["Description"] = GetProductDescription(productGroupFromDB, productGroup, siteCode);
                row.EndEdit();
                dt.Rows.Add(row);
            }

            var displayName = "Product_Export_" + DateTime.Today.ToString(SystemConfiguration.DateFormat) + ".xls";
            var fileName = Path.Combine(Server.MapPath("~/Export/"), displayName);
            DataImportService.Export(fileName, dt);


            FileUtilities.DownloadFile(File.ReadAllBytes(fileName), displayName);
        }

        string GetProductTitle(ProductgroupEntity entity, ProductgroupEntity originalEntity, int siteCode)
        {

            //标题=[SKU吊牌信息]+（货号 英文标题)+[SKU英文颜色]+[SKU标题尺码]
            var htmlService = new HtmlToolService();
            var brandSettingEntity = htmlService.GetBrandSetting(siteCode);
            if (!ckbIsForced.Checked)
            {
                if (brandSettingEntity == null)
                {
                    throw new ApplicationException(string.Format("设置错误-标题中吊牌没有设定，商品名称{0}", originalEntity.Productname));
                }
            }

            var brand = originalEntity.Productname.Contains("吊牌")
                ? brandSettingEntity == null ? string.Empty : brandSettingEntity.Titlebrand
                            : brandSettingEntity == null ? string.Empty : brandSettingEntity.Titlenobrand;




            var titleSetting = htmlService.GetTitleColorSetting(entity.Color);
            if (!ckbIsForced.Checked)
            {
                if (titleSetting == null || string.IsNullOrWhiteSpace(titleSetting.Colortitle))
                {
                    throw new ApplicationException(string.Format("设置错误-标题颜色英文没有设定，颜色:{0},商品名称:{1}", entity.Color, originalEntity.Productname));
                }
            }
            var titleColor = titleSetting == null ? string.Empty : titleSetting.Colortitle;

            var sizeSetting = htmlService.GetSizeSetting(originalEntity.Size, siteCode);
            if (!ckbIsForced.Checked)
            {
                if (sizeSetting == null || string.IsNullOrWhiteSpace(sizeSetting.Sizetitle))
                {
                    throw new ApplicationException(string.Format("设置错误-标题尺码没有设定，规格:{0},商品名称:{1}", originalEntity.Size, originalEntity.Productname));
                }
            }
            var sizeTitle = sizeSetting == null ? string.Empty : sizeSetting.Sizetitle;

            var sb = new StringBuilder();
            sb.Append(brand);
            sb.Append(" ");
            sb.Append(entity.Itemno);
            sb.Append(" ");
            sb.Append(entity.Englishtitle);
            sb.Append(" ");
            sb.Append(titleColor);
            sb.Append(" ");
            sb.Append(sizeTitle);

            return sb.ToString();

        }

        string GetProductDescription(ProductgroupEntity entity, ProductgroupEntity originalEntity, int siteCode)
        {
            var htmlAccountService = new HtmlToolAccountService();

            if (!entity.Categoryruleid.HasValue)
            {
                if (ckbIsForced.Checked)
                    return string.Empty;
                throw new ApplicationException(string.Format("设置错误-HtmlTool分类没有选择，商品名称:{0}", originalEntity.Productname));
            }
            var htmlAccountTemplate = htmlAccountService.GetHtmlToolAccountTemplate(ddlAcount.SelectedValue.ToInt32().Value, entity.Categoryruleid.Value);

            var template = new TemplateEntity();
            if (!htmlAccountTemplate.Content.HasValue)
            {
                if (ckbIsForced.Checked)
                    return string.Empty;
                throw new ApplicationException(string.Format("设置错误-该账号对应的商品分类{1}没有设置描述模版，商品名称:{0}", originalEntity.Productname, originalEntity.Htmltoolcategoryrule.Category));
            }

            template.FetchUsingPK(htmlAccountTemplate.Content.Value);

            var htmlService = new HtmlToolService();
            var brandSettingEntity = htmlService.GetBrandSetting(siteCode);

            if (!ckbIsForced.Checked)
            {
                if (brandSettingEntity == null)
                {
                    throw new ApplicationException(string.Format("设置错误-描述中吊牌没有设定，商品名称:{0}", originalEntity.Productname));
                }
            }
            if (!ckbIsForced.Checked)
            {
                if (!entity.Trademarkid.HasValue)
                {
                    throw new ApplicationException(string.Format("设置错误-品牌没有选择，商品名称为{0}",
                                                                 originalEntity.Productname));
                }
            }

            var result = template.Description.ReplaceText1("<O:TEXT1>品牌<O:TEXT1>", _htmlToolService.GetTradeMarkById(entity.Trademarkid));
            result = result.ReplaceText1("<O:TEXT1>有无吊牌<O:TEXT1>", originalEntity.Productname.Contains("吊牌")
                ? brandSettingEntity == null ? string.Empty : brandSettingEntity.Descbrand
                : brandSettingEntity == null ? string.Empty : brandSettingEntity.Descnobrand);

            var sizeSetting = htmlService.GetSizeSetting(originalEntity.Size, siteCode);

            if (!ckbIsForced.Checked)
            {
                if (sizeSetting == null || string.IsNullOrWhiteSpace(sizeSetting.Sizedescription))
                {
                    throw new ApplicationException(string.Format("设置错误-描述中尺码没有设定，规格:{0}，商品名称:{1}", originalEntity.Size, originalEntity.Productname));
                }
            }

            result = result.ReplaceText1("<O:TEXT1>尺码</O:TEXT1>", sizeSetting == null ? string.Empty : sizeSetting.Sizedescription);

            result = result.ReplaceText1("<O:TEXT1>市场</O:TEXT1>", entity.Market);
            result = result.ReplaceText1("<O:TEXT1>货号</O:TEXT1>", entity.Itemno);
            result = result.ReplaceText1("<O:TEXT1>特征</O:TEXT1>", entity.Specifics);
            result = result.ReplaceText1("<O:TEXT1>零售价</O:TEXT1>", entity.Retailprice);
            result = result.ReplaceText1("<O:TEXT1>英文标题</O:TEXT1>", entity.Englishtitle);



            result = result.ReplaceText1("<O:TEXT1>材料</O:TEXT1>", entity.Material);
            result = result.ReplaceText1("<O:TEXT1>注意</O:TEXT1>", entity.Comment);
            result = result.ReplaceHtml("<O:HTML>描述</O:HTML>", entity.Description);
            result = result.ReplaceText1("<O:TEXT1>规格</O:TEXT1>", originalEntity.Size);


            result = result.ReplaceImg("<O:IMAGE>尺码表</O:IMAGE>", entity.Sizetable);


            result = result.ReplaceImg("<O:IMAGE>图片1</O:IMAGE>", entity.Picurl1);

            result = result.ReplaceImg("<O:IMAGE>图片2</O:IMAGE>", entity.Picurl2);

            result = result.ReplaceImg("<O:IMAGE>图片3</O:IMAGE>", entity.Picurl3);

            result = result.ReplaceImg("<O:IMAGE>图片4</O:IMAGE>", entity.Picurl4);

            result = result.ReplaceImg("<O:IMAGE>图片5</O:IMAGE>", entity.Picurl5);

            result = result.ReplaceImg("<O:IMAGE>图片6</O:IMAGE>", entity.Picurl6);

            result = result.ReplaceImg("<O:IMAGE>图片7</O:IMAGE>", entity.Picurl7);

            result = result.ReplaceImg("<O:IMAGE>图片8</O:IMAGE>", entity.Picurl8);

            result = result.ReplaceImg("<O:IMAGE>图片9</O:IMAGE>", entity.Picurl9);

            result = result.ReplaceImg("<O:IMAGE>图片10</O:IMAGE>", entity.Picurl10);

            result = result.ReplaceImg("<O:IMAGE>图片11</O:IMAGE>", entity.Picurl11);

            result = result.ReplaceImg("<O:IMAGE>图片12</O:IMAGE>", entity.Picurl12);

            return result;

        }

        protected string GetDictionaryItemName(object id)
        {
            if (MiscUtilities.IsNullOrEmpty(id)) return string.Empty;
            var service = new DictionaryService();
            var item = service.GetDataItem(id.ToString().ToInt32() ?? 0);

            return item == null ? string.Empty : item.Name;

        }
        protected string GetImageUrl(object id)
        {
            if (MiscUtilities.IsNullOrEmpty(id)) return string.Empty;

            var baseUrl = System.Configuration.ConfigurationSettings.AppSettings["picThumbnailUrl"];
            return string.Format(baseUrl, id);
        }


    }
}